angular.module('starter')
  .factory("YdzBase", ["$http",
    function(http) {
      var SERVER = "http://www.duo-shao.com:8080";
      var _result = {
        cities: ["北京", "深圳", "哈尔滨"],
        salerList: [],
        tailorList: [],
        products_list: [
          "西服", "西服3件套", "衬衫", "单西", "西裤", "马甲", "礼服",
          "长风衣",
          "中风衣",
          "短风衣",
          "燕尾服", "夹克",
          "皮鞋", "领带夹", "领带", "袖扣", "口袋巾"
        ],
        fabricList: ["LESS&MORE",
          "THOMAS MASON", "SCABAL", "VBC", "ZEGNA",
          "DECHAMPS 1857", "HOLLAND&SHERRY", "MARZONI", "鲁泰",
          "CERRUTI 1881", "DORMEUIL",
          "HAI LAN", "PUKUN", "世元进口精选",
          "HARRISONS OF EDINGURGH", "PORTER AND HARDING", "W. BILL",
          "H.LESSER&SONS", "CACCIOPPOLI", "REDA", "FISIL",
          "ALUMO", "CANCLINI"
        ]
      };
      var success = {
        cities: false,
        salerList: false,
        tailorList: false,
        products_list: false,
        fabricList: false
      };

      return {
        getCities: function(cbk) {
          tryOnce("cities",
            "/json/get_info/city_list?callback=JSON_CALLBACK",
            "城市列表", cbk)
        },
        getEmployee: function(job, area, cbk) {
          var propName = job + "List" + area;
          if (!success[propName]) {
            http.jsonp(SERVER + "/json/get_all_" + job +
              "?a=" + area +
              "&callback=JSON_CALLBACK").
            then(function(res) {
                var data = res.data;
                if (!!data && data.length > 0) {
                  success[propName] = true;
                  _result[propName] = data;
                } else {
                  alert(job + "列表为空！")
                }
                if (angular.isFunction(cbk)) {
                  cbk(_result[propName])
                }
              },
              function() {
                alert("网络异常！")
              })
          } else {
            if (angular.isFunction(cbk)) {
              cbk(_result[propName])
            }
          }
        },
        getProductsList: function(cbk) {
          tryOnce("products_list",
            "/json/get_info/products_list?callback=JSON_CALLBACK",
            "产品列表", cbk)
        },
        getPriceAlgo: function(cbk) {
          var propName = "compute_price_funcs";
          if (!success[propName]) {
            http.jsonp(SERVER +
                "/json/get_info/compute_price?callback=JSON_CALLBACK")
              .then(function(res) {
                  var data = res.data;
                  if (!!data && !!data.D) {
                    success[propName] = true;
                    _result[propName] = data.D;
                  } else {
                    alert("计算价格函数列表为空：" + data.E)
                  }
                  if (angular.isFunction(cbk)) {
                    cbk(_result[propName])
                  }
                },
                function() {
                  alert("网络异常！")
                })
          } else {
            if (angular.isFunction(cbk)) {
              cbk(_result[propName])
            }
          }
        },
        getFabricPrice: function(cbk) {
          if (!success.fabricPrice) {
            http.jsonp(SERVER +
                "/json/all_fabric_price?callback=JSON_CALLBACK")
              .then(function(res) {
                  var data = res.data;
                  if (!data.Error) {
                    _result.fabricPrice = data.All;
                    success.fabricPrice = true;
                  } else {
                    alert("获取面料价格失败：" + data.Error);
                    _result.fabricPrice = [];
                  }
                  if (angular.isFunction(cbk)) {
                    cbk(_result.fabricPrice)
                  }
                },
                function() {
                  alert("网络异常！")
                });
          } else {
            if (angular.isFunction(cbk)) {
              cbk(_result.fabricPrice)
            }
          }
        },
        getFabricList: function(cbk) {
          if (!success.fabricList) {
            http.jsonp(
              SERVER +
              "/json/get_supplier_field?db=fabric_supplier&f=fabriclist&callback=JSON_CALLBACK"
            ).
            then(function(res) {
                var ret = res.data;
                if (!!ret.Error) {
                  alert("获取面料列表失败：" + ret.Error + "，使用旧数据！")
                } else {
                  var _fabriclist = [];
                  ret.data.forEach(function(item) {
                    fl = item.fabriclist.split(", ")
                    fl.forEach(function(list_item) {
                      if (_fabriclist.indexOf(list_item) < 0) {
                        _fabriclist.push(list_item)
                      }
                    })
                  })
                  if (_fabriclist.length > 0) {
                    console.log("获取面料列表成功：" + _fabriclist);
                    _result.fabricList = _fabriclist;
                    success.fabricList = true;
                  } else {
                    alert("获取面料列表失败：" + ret.Error + "，使用旧数据！")
                  }
                }
                if (angular.isFunction(cbk)) {
                  cbk(_result.fabricList);
                }
              },
              function() {
                alert("网络异常！")
              })
          } else {
            if (angular.isFunction(cbk)) {
              console.log("跳过get，使用新数据")
              cbk(_result.fabricList);
            }
          }
        }
      }

      function tryOnce(task_name, url, anotate, cbk) {
        if (!success[task_name]) {
          http.jsonp(SERVER + url).
          then(function(res) {
              var ret = res.data;
              if (!!ret.E) {
                alert("获取" + anotate + "失败：" + ret.E + " 使用旧数据！")
              } else {
                var _list = ret.D.split(",");
                if (!!_list && _list.length > 0) {
                  _result[task_name] = _list;
                  console.log("获取" + anotate + "成功: " + _list);
                  success[task_name] = true;
                } else {
                  alert("获取" + anotate + "失败：" + ret.E +
                    " 使用旧数据！")
                }
              }
              if (angular.isFunction(cbk)) {
                cbk(_result[task_name]);
              }
            },
            function() {
              alert("网络异常！")
            })
        } else {
          if (angular.isFunction(cbk)) {
            console.log("跳过get请求，使用新" + anotate)
            cbk(_result[task_name]);
          }
        }
      }
    }
  ])
